// components/search/index.js

import { KeywordsModel } from '../../models/KeywordsModel'
import { BookModel } from '../../models/BookModel'
import { paginationBev } from '../behavior/pagination'
const keywordsModel = new KeywordsModel()
const bookModel = new BookModel()

Component({
    /**
   * 组件的属性列表
   */
    behaviors: [paginationBev],
    properties: {
        more: {
            type: String,
            observer: 'loadMore'

        }
    },

    /**
   * 组件的初始数据
   */
    data: {
        historyWords: [],
        searching: false,
        q: '',
        hotWords: [],
        loadingCenter: false
    },

    attached () {
        this.setData({
            historyWords: keywordsModel.getHistory()
        })

        keywordsModel.getHot().then(res => {
            this.setData({
                hotWords: res.data.hot
            })
        })
    },

    /**
   * 组件的方法列表
   */
    methods: {

        loadMore () {
            if (!this.data.q) {
                return
            }
            if (this.isLocked()) {
                return
            }
            if (this.hasMore()) {
                this.locked()
                bookModel.getSearch(this.getCurrentStart(), this.data.q)
                    .then(res => {
                        this.setMoreData(res.data.books)
                        this.unLocked()
                    }, () => {
                        this.unLocked()
                    })
            }
        },

        onCancel () {
            this.initialize()
            this.triggerEvent('cancel', {}, {})
        },

        onConfirm (event) {
            let q = event.detail.value || event.detail.content

            if (!q) {
                return
            }
            this.setData({
                q
            })
            this._showLoadingCenter()
            this._showResult()
            bookModel.getSearch(0, q)
                .then(res => {
                    keywordsModel.setHistory(q)
                    this._hideLoadingCenter()
                    this.setMoreData(res.data.books)
                    this.setTotal(res.data.total)
                })
        },
        onDelete () {
            this.initialize()
            this._closeResult()
        },

        _showLoadingCenter () {
            this.setData({
                loadingCenter: true
            })
        },

        _hideLoadingCenter () {
            this.setData({
                loadingCenter: false
            })
        },

        _showResult () {
            this.setData({
                searching: true
            })
        },

        _closeResult () {
            this.setData({
                searching: false,
                q: ''
            })
        }

    }
})
